<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.question" placeholder="题目" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                新增题目
            </el-button>
            <el-button class="filter-item" type="danger" icon="el-icon-delete" :disabled="!selectedRows.length"
                @click="handleBatchDelete">
                批量删除
            </el-button>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="题目" prop="question" />
            <el-table-column label="选项" min-width="300">
                <template slot-scope="{row}">
                    <div v-for="(option, index) in row.options" :key="index">
                        {{ String.fromCharCode(65 + index) }}. {{ option }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="正确答案" prop="correctAnswer" />
            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
                <el-form-item label="题目" prop="question">
                    <el-input v-model="temp.question" type="textarea" :rows="2" />
                </el-form-item>
                <el-form-item label="选项A" prop="optionA">
                    <el-input v-model="temp.optionA" />
                </el-form-item>
                <el-form-item label="选项B" prop="optionB">
                    <el-input v-model="temp.optionB" />
                </el-form-item>
                <el-form-item label="选项C" prop="optionC">
                    <el-input v-model="temp.optionC" />
                </el-form-item>
                <el-form-item label="选项D" prop="optionD">
                    <el-input v-model="temp.optionD" />
                </el-form-item>
                <el-form-item label="正确答案" prop="correctAnswer">
                    <el-select v-model="temp.correctAnswer" placeholder="请选择正确答案">
                        <el-option label="A" value="A" />
                        <el-option label="B" value="B" />
                        <el-option label="C" value="C" />
                        <el-option label="D" value="D" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    确定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { fetchList, createQuestion, updateQuestion, deleteQuestion, batchDeleteQuestions } from '@/api/question-bank'
import Pagination from '@/components/Pagination'

export default {
    name: 'QuestionBank',
    components: { Pagination },
    data() {
        return {
            list: null,
            total: 0,
            listLoading: true,
            selectedRows: [],
            listQuery: {
                page: 1,
                limit: 20,
                question: undefined
            },
            dialogVisible: false,
            dialogStatus: '',
            dialogTitle: '',
            temp: {
                id: undefined,
                question: '',
                optionA: '',
                optionB: '',
                optionC: '',
                optionD: '',
                correctAnswer: ''
            },
            rules: {
                question: [{ required: true, message: '请输入题目', trigger: 'blur' }],
                optionA: [{ required: true, message: '请输入选项A', trigger: 'blur' }],
                optionB: [{ required: true, message: '请输入选项B', trigger: 'blur' }],
                optionC: [{ required: true, message: '请输入选项C', trigger: 'blur' }],
                optionD: [{ required: true, message: '请输入选项D', trigger: 'blur' }],
                correctAnswer: [{ required: true, message: '请选择正确答案', trigger: 'change' }]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            this.listLoading = true
            try {
                // const { data } = await fetchList(this.listQuery)
                // this.list = data.items
                // this.total = data.total

                // 测试数据
                this.list = [
                    {
                        id: 1,
                        question: '测试题目1',
                        options: ['选项A', '选项B', '选项C', '选项D'],
                        correctAnswer: 'A'
                    },
                    {
                        id: 2,
                        question: '测试题目2',
                        options: ['选项A', '选项B', '选项C', '选项D'],
                        correctAnswer: 'B'
                    },
                    {
                        id: 3,
                        question: '测试题目3',
                        options: ['选项A', '选项B', '选项C', '选项D'],
                        correctAnswer: 'C'
                    },
                    {
                        id: 4,
                        question: '测试题目4',
                        options: ['选项A', '选项B', '选项C', '选项D'],
                        correctAnswer: 'D'
                    }
                ]
                this.total = 4

                // 实际API调用
                // const { data } = await fetchList(this.listQuery)
                // this.list = data.items
                // this.total = data.total
            } catch (error) {
                console.error('获取题目列表失败:', error)
            }
            this.listLoading = false
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                question: '',
                optionA: '',
                optionB: '',
                optionC: '',
                optionD: '',
                correctAnswer: ''
            }
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogTitle = '新增题目'
            this.dialogVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate(async (valid) => {
                if (valid) {
                    try {
                        const options = [this.temp.optionA, this.temp.optionB, this.temp.optionC, this.temp.optionD]
                        await createQuestion({
                            question: this.temp.question,
                            options: options,
                            correctAnswer: this.temp.correctAnswer
                        })
                        this.dialogVisible = false
                        this.$notify({
                            title: '成功',
                            message: '创建成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    } catch (error) {
                        console.error('创建题目失败:', error)
                    }
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row)
            this.temp.optionA = row.options[0]
            this.temp.optionB = row.options[1]
            this.temp.optionC = row.options[2]
            this.temp.optionD = row.options[3]
            this.dialogStatus = 'update'
            this.dialogTitle = '编辑题目'
            this.dialogVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate(async (valid) => {
                if (valid) {
                    try {
                        const options = [this.temp.optionA, this.temp.optionB, this.temp.optionC, this.temp.optionD]
                        await updateQuestion(this.temp.id, {
                            question: this.temp.question,
                            options: options,
                            correctAnswer: this.temp.correctAnswer
                        })
                        this.dialogVisible = false
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    } catch (error) {
                        console.error('更新题目失败:', error)
                    }
                }
            })
        },
        async handleDelete(row) {
            try {
                await this.$confirm('确认删除该题目吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                await deleteQuestion(row.id)
                this.$notify({
                    title: '成功',
                    message: '删除成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除题目失败:', error)
                }
            }
        },
        handleSelectionChange(rows) {
            this.selectedRows = rows
        },
        async handleBatchDelete() {
            if (this.selectedRows.length === 0) {
                this.$message.warning('请选择要删除的题目')
                return
            }
            try {
                await this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条题目吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                const ids = this.selectedRows.map(row => row.id)
                await batchDeleteQuestions(ids)
                this.$notify({
                    title: '成功',
                    message: '批量删除成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('批量删除题目失败:', error)
                }
            }
        }
    }
}
</script>

<style scoped>
.filter-container {
    padding-bottom: 10px;
}

.filter-item {
    margin-right: 10px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style> 